package com.naizhuai.util;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.naizhuai.AppContext;

import java.lang.reflect.Field;

/**
 * @author：lichenxi
 * @date 2018/2/22 11
 * email：525603977@qq.com
 * Fighting
 */
public class ToastCompat {
    private static Field sField_TN ;
    private static Field sField_TN_Handler ;

    static {
        try {
            sField_TN = Toast.class.getDeclaredField("mTN");
            sField_TN.setAccessible(true);
            sField_TN_Handler = sField_TN.getType().getDeclaredField("mHandler");
            sField_TN_Handler.setAccessible(true);
        } catch (Exception e) {}
    }


    private static void hook(Toast toast) {
        try {
            Object tn = sField_TN.get(toast);
            Handler preHandler = (Handler)sField_TN_Handler.get(tn);
            sField_TN_Handler.set(tn,new NoExceptionHandlerWarpper(preHandler));
        } catch (Exception e) {}
    }

    public static void showToast(Context context, CharSequence cs, int length) {
        Toast toast = Toast.makeText(AppContext.app,cs,length);
        hook(toast);
        toast.show();
    }

    private static class NoExceptionHandlerWarpper extends Handler {

        private Handler mHandler;

        public NoExceptionHandlerWarpper(Handler impl) {
            this.mHandler = impl;
        }

        @Override
        public void dispatchMessage(Message msg) {
            try {
                super.dispatchMessage(msg);
            } catch (Exception e) {}
        }

        @Override
        public void handleMessage(Message msg) {
            mHandler.handleMessage(msg);//需要委托给原Handler执行
        }
    }
}
